#! usr/bin/perl -w
use strict;

sub param
{
	#file and threshold
	print "file name : ";
	my $LDfilename=<STDIN>;
	chomp $LDfilename;
	print "threshold : ";
	my $threshold=<STDIN>;
	chomp $threshold;
	return($LDfilename,$threshold)
}

sub main{

my($LDfilename,$threshold)=&param();

my $firstLine=1;
my @indep_list=();
my @other_list=();

open(LDFILE, $LDfilename) or die "cannot open $LDfilename";
open(OUTPUT1,">SNP_in.txt") or die "cannot create outputfile";
open(OUTPUT2,">SNP_del.txt") or die "cannot create outputfile";

while(my $line=<LDFILE>)
{
        chomp($line);
        $line=~ s/ +/ /gi;#separate rows with a whitespace only
        my @fields=split(/ /,$line);
        
	if($firstLine!=1) #not first line
        {	
		# data
		my $R2=$fields[(scalar@fields)-1];# fields R2
        	my $SNPid1=$fields[3];
        	my $SNPid2=$fields[6];

		#exist in indep_list
		my @match1=grep(/^$SNPid1$/ig,@indep_list);#search SNPid in list of independent SNP
       		my @match2=grep(/^$SNPid2$/ig,@indep_list);
        	#exist in other_list
		my @exist1=grep(/^$SNPid1$/ig,@other_list);
        	my @exist2=grep(/^$SNPid2$/ig,@other_list);
	
		if($R2 ge $threshold)
		{
			if((scalar@match1 eq 0)and(scalar@match2 eq 0)and(scalar@exist1 eq 0))
			{
				push(@indep_list,$SNPid1);
				print OUTPUT1 $SNPid1."\n";
				if(scalar@exist2 eq 0)
				{
					push(@other_list,$SNPid2);
                       			print OUTPUT2 $SNPid2."\n";
				}
			}	
			if((scalar@match1 ge 1)and(scalar@match2 eq 0))
			{
				if(scalar@exist2 eq 0)
				{
					push(@other_list,$SNPid2);
                                	print OUTPUT2 $SNPid2."\n";
				}
			}
		 	if((scalar@match1 eq 0)and(scalar@match2 ge 1))
                	{
                        	if(scalar@exist1 eq 0)
                        	{
                                	push(@other_list,$SNPid1);
                                	print OUTPUT2 $SNPid1."\n";
                        	}
                	}
		}
		else
		{
			if(scalar@match1 eq 0)
			{
				push(@indep_list,$SNPid1);
                        	print OUTPUT1 $SNPid1."\n";
			}
			if(scalar@match2 eq 0)
			{
				push(@indep_list,$SNPid2);
                       		print OUTPUT1 $SNPid2."\n";
			}	
		}
	}
        $firstLine=0;
}


close LDFILE;
close OUTPUT1;
close OUTPUT2;

print "\nsee independent SNPs in the output file \"SNP_in.txt\" and others in \"SNP_del.txt\" \n\n";


exit;
}

main();
